<!DOCTYPE html >
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>websocket客户端</title>
</head>
<body>
<script type="text/javascript">
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8888/ws");
        socket.onmessage = function (ev) {
            var ta = document.getElementById("responseText");
            ta.value = ta.value + "\n" + ev.data;
        }
        socket.onopen = function (ev) {
            var ta = document.getElementById("responseText");
            ta.value = ta.value + "\n" + "链接开启";
            startHeartBeat();
        }
        socket.onclose = function (ev) {
            var ta = document.getElementById("responseText");
            ta.value = ta.value + "\n" + "链接关闭";
        }

    } else {
        alert("不支持websocket")
    }

    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("链接尚未开启！")
        }

    }

    function startHeartBeat() {
        setInterval(
            function () {
                socket.send("ping");
            }
            , 6000);


    }

</script>
<form>
    <textarea name="message" style="width: 400px;height: 200px"></textarea>
    <input type="button" value="发送数据" onclick="send(this.form.message.value)"/>

    <h3>服务端输出：</h3>
    <textarea id="responseText" style="width: 400px;height: 200px"></textarea>
    <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value='清空内容'/>

</form>

</body>
</html>